// src/utils/requestManager.ts
import axios, {AxiosRequestConfig} from 'axios';

interface PendingRequest {
    url: string;
    method: string;
    params: any;
    data: any;
    cancel: (message?: string) => void;
}

const pendingRequests: PendingRequest[] = [];

/**
 * 生成请求的唯一标识
 */
const generateRequestKey = (config: AxiosRequestConfig) => {
    const {url, method, params, data} = config;
    return [
        url,
        method,
        JSON.stringify(params),
        JSON.stringify(data)
    ].join('&');
};

/**
 * 添加请求到pending列表
 */
export const addPendingRequest = (config: AxiosRequestConfig) => {
    const requestKey = generateRequestKey(config);

    // 检查是否有重复请求
    const existingRequestIndex = pendingRequests.findIndex(
        request => request.url === config.url &&
            request.method === config.method &&
            JSON.stringify(request.params) === JSON.stringify(config.params) &&
            JSON.stringify(request.data) === JSON.stringify(config.data)
    );

    // 如果存在重复请求，则取消之前的请求
    if (existingRequestIndex !== -1) {
        pendingRequests[existingRequestIndex].cancel('请求被取消: 重复请求');
        pendingRequests.splice(existingRequestIndex, 1);
    }

    // 为当前请求创建cancel token
    const source = axios.CancelToken.source();
    config.cancelToken = config.cancelToken || source.token;

    // 将请求添加到pending列表
    pendingRequests.push({
        url: config.url || '',
        method: config.method || '',
        params: config.params || {},
        data: config.data || {},
        cancel: source.cancel
    });
};

/**
 * 从pending列表中移除请求
 */
export const removePendingRequest = (config: AxiosRequestConfig) => {
    const requestKey = generateRequestKey(config);

    const existingRequestIndex = pendingRequests.findIndex(
        request => request.url === config.url &&
            request.method === config.method &&
            JSON.stringify(request.params) === JSON.stringify(config.params) &&
            JSON.stringify(request.data) === JSON.stringify(config.data)
    );

    if (existingRequestIndex !== -1) {
        pendingRequests.splice(existingRequestIndex, 1);
    }
};

/**
 * 取消所有pending请求
 */
export const cancelAllPendingRequests = () => {
    pendingRequests.forEach(request => {
        request.cancel('请求被取消: 页面卸载');
    });
    pendingRequests.length = 0;
};